/**
 * 代码库信息概览
 * isEmptyProject 参数决定是否使用emptyClone.jsx
 */

import React from 'react';
import { ENUM, PROJECT_ADMIN_ROLES } from 'utils/constants.js';
import { Button, Tag, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import dayjs from 'dayjs';
import track from 'utils/track';
import { access } from 'components/accessContainer/util';
import WebIdeBtn from '../content/components/webIdeBtn';
import { getWebIdeUrl } from 'api';
import utils from 'utils';
import CloneBtn from './cloneBtn';
import EmptyClone from './emptyClone';
import './index.scss';
import { navigate, navigateOpen } from 'utils/router';
import FlowBtn from './flowBtn';
import NewAndUploadFile from './newAndUploadFile';
import intl from '../../../../../../../../locale';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';

const { Tooltip } = Balloon;
const { resourceSubject, pathResource } = window.FORCE;
const { visibility_levels } = ENUM;
const { role } = window.FORCE.pathResource;

export default class RepoOverviewInfo extends React.Component {
  filterLevel = (level) => {
    let label = '';
    visibility_levels.forEach((item) => {
      if (item.value === Number(level)) {
        label = item.label;
      }
    });
    return label;
  };

  goWebIde = (e, path) => {
    const { projectInfo } = this.props;
    const admin_setting_language = projectInfo && projectInfo.admin_setting_language;
    const template = utils.getAdminSettingLanguage(admin_setting_language);
    const { revisionType } = resourceSubject;
    e.preventDefault();
    getWebIdeUrl({
      filepath: path,
      branch: revisionType === 'branch' ? resourceSubject.revision : '',
      commit: revisionType === 'sha1' ? resourceSubject.revision : '',
      line: '',
      column: '',
      type: template,
      merge_commit: '',
      mergerequestId: '',
    })
      .then((result) => {
        const url = result.endpoint;
        navigateOpen(url);
      })
      .catch((err) => {
        console.error(err);
      });
  };

  goNew = () => {
    const revision = resourceSubject.revision || 'master';
    navigate(
      `/${pathResource.fullPath}/new/${utils.revisionEncodeURI(revision)}/${resourceSubject.path}`,
    );

    this.props.updateSetSelectedType({
      resourceSubject: {
        subject: 'new',
        path: resourceSubject.path,
      },
    });
  };

  goMirrorSync = () => {
    navigate(`/${pathResource.fullPath}/settings/mirror_sync`);
  };

  openMirrorSyncDocs = () => {
    navigateOpen(docs('warehouseSynchronization'), '_blank');
  };

  renderStatus = (status) => {
    switch (status) {
      case 'SUCCESS':
        return intl.get({
          id: 'code-assets.containers.repoOverviewInfo.Success',
          defaultMessage: '成功',
        });
      case 'FAIL':
        return intl.get({
          id: 'code-assets.containers.repoOverviewInfo.Failed',
          defaultMessage: '失败',
        });
      case 'READY':
        return intl.get({
          id: 'code-assets.containers.repoOverviewInfo.WaitingForSynchronization',
          defaultMessage: '等待同步',
        });
      case 'SYNCHRONIZING':
        return intl.get({
          id: 'code-assets.containers.repoOverviewInfo.Synchronizing',
          defaultMessage: '同步中',
        });
      default:
        break;
    }
  };

  renderMirrorSync = () => {
    const { lastMirrorSyncRecord, mirrorSyncSetting } = this.props;
    if (!mirrorSyncSetting || !mirrorSyncSetting.enabled) {
      return null;
    }
    const isAdmin = access(PROJECT_ADMIN_ROLES, role);
    const cursorClass = isAdmin
      ? 'overview-info-mirror-sync-pointer'
      : 'overview-info-mirror-sync-pointer-disabled';
    if (lastMirrorSyncRecord.sync_status === null) {
      return (
        <Tooltip
          style={{ width: isAdmin ? '320px' : '400px' }}
          className="overview-info-mirror-sync"
          align="bl"
          trigger={
            <Tag className={cursorClass}>
              <YunxiaoIcon type="refresh-line" className="arrows-cycle-icon" />
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.Synchronous',
                defaultMessage: '同步',
              })}
            </Tag>
          }
          text={
            <div className="overview-info-mirror-sync-tooltip">
              <div className="overview-info-mirror-sync-tooltip-time">
                {intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.NoSynchronizationRecordsAreFound',
                  defaultMessage: '暂无同步记录',
                })}
              </div>
              <div className="overview-info-mirror-sync-tooltip-desc">
                {isAdmin ? (
                  <>
                    <span>
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.ForceSynchronousImportOfSource',
                        defaultMessage: '强制同步导入来源仓库内容',
                      })}
                    </span>
                    <Button type="primary" text className="btn" onClick={this.goMirrorSync}>
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.GoToSync',
                        defaultMessage: '前往同步',
                      })}
                    </Button>
                  </>
                ) : (
                  <>
                    <span>
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.ForciblyImportTheContentOf',
                        defaultMessage: '强制同步导入来源仓库内容, 请联系管理员操作',
                      })}
                    </span>
                    <Button type="primary" text className="btn" onClick={this.openMirrorSyncDocs}>
                      {intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.LearnMore',
                        defaultMessage: '了解更多',
                      })}
                    </Button>
                  </>
                )}
              </div>
            </div>
          }
        />
      );
    } else if (
      lastMirrorSyncRecord.sync_status === 'READY' ||
      lastMirrorSyncRecord.sync_status === 'SYNCHRONIZING'
    ) {
      return (
        <Tooltip
          align="bl"
          style={{ maxWidth: 300 }}
          className="overview-info-mirror-sync"
          trigger={
            <Tag className="overview-info-mirror-sync-disabled">
              <YunxiaoIcon type="refresh-line" className="arrows-cycle-icon" />
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.Synchronizing',
                defaultMessage: '同步中',
              })}
            </Tag>
          }
          text={
            <div>
              {intl.get({
                id: 'code-assets.containers.repoOverviewInfo.DatabaseSynchronizationIsInProgress',
                defaultMessage: '仓库同步中，为保证数据一致性，暂时禁止仓库写入，请耐心等待',
              })}
            </div>
          }
        />
      );
    }
    return (
      <Tooltip
        style={{ width: isAdmin ? '420px' : '500px' }}
        className="overview-info-mirror-sync"
        align="bl"
        trigger={
          <Tag className={cursorClass}>
            <YunxiaoIcon type="refresh-line" className="arrows-cycle-icon" />
            {intl.get({
              id: 'code-assets.containers.repoOverviewInfo.Synchronous',
              defaultMessage: '同步',
            })}
          </Tag>
        }
        text={
          <div className="overview-info-mirror-sync-tooltip">
            {lastMirrorSyncRecord.gmt_modified ? (
              <div className="overview-info-mirror-sync-tooltip-time">
                {intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.LastSynchronizationTime',
                  defaultMessage: '最近同步时间：',
                })}

                {dayjs(lastMirrorSyncRecord.gmt_modified).format('YYYY-MM-DD HH:mm:ss')}
                {intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.SynchronizationResults',
                  defaultMessage: '同步结果：',
                })}

                {this.renderStatus(lastMirrorSyncRecord.sync_status)}
              </div>
            ) : null}
            <div className="overview-info-mirror-sync-tooltip-desc">
              {isAdmin ? (
                <>
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.ForceSynchronousImportOfSource',
                      defaultMessage: '强制同步导入来源仓库内容',
                    })}
                  </span>
                  <Button type="primary" text className="btn" onClick={this.goMirrorSync}>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.GoToSync',
                      defaultMessage: '前往同步',
                    })}
                  </Button>
                </>
              ) : (
                <>
                  <span>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.ForciblyImportTheContentOf',
                      defaultMessage: '强制同步导入来源仓库内容, 请联系管理员操作',
                    })}
                  </span>
                  <Button type="primary" text className="btn" onClick={this.openMirrorSyncDocs}>
                    {intl.get({
                      id: 'code-assets.containers.repoOverviewInfo.LearnMore',
                      defaultMessage: '了解更多',
                    })}
                  </Button>
                </>
              )}
            </div>
          </div>
        }
      />
    );
  };

  flowButtonComponent = (params = {}) => {
    if (getFeature('module_enable.repository.flow')) {
      return [<FlowBtn {...this.props} {...params} />];
    }
    return [];
  };

  render() {
    const {
      projectInfo,
      isInitedLeftTree,
      treeData,
      isEmptyProject,
      ipSetting,
      project_clone_download,
      foldBtn,
    } = this.props;
    const { isArchive } = pathResource;

    let fullName = '';

    const arr = pathResource.fullName.split('/');
    const { length } = arr;
    fullName = arr[length - 1] ? arr[length - 1].trim() : '';

    const leftMaxWidth = foldBtn ? 'calc(100% - 144px)' : 'calc(100% - 367px)';

    return (
      <div className={`overview-info ${isEmptyProject ? 'empty' : ''}`}>
        <div style={{ display: 'flex', alignItems: 'center', maxWidth: leftMaxWidth }}>
          <Tooltip trigger={<div className="overview-info-title">{fullName}</div>} align="b">
            {fullName}
          </Tooltip>
          <div className="overview-info-infobar">
            {projectInfo.demo_project ? (
              <Tag>
                {intl.get({
                  id: 'code-assets.containers.repoOverviewInfo.SampleCodeLibrary',
                  defaultMessage: '示例代码库',
                })}
              </Tag>
            ) : null}
            <Tag>{this.filterLevel(projectInfo.visibility_level)}</Tag>
            {this.renderMirrorSync()}
          </div>
        </div>
        {isEmptyProject ? (
          <EmptyClone {...this.props} />
        ) : (
          <div className="overview-info-toolbar">
            <div>
              {isArchive === 'false' && !foldBtn ? (
                <React.Fragment>
                  {isInitedLeftTree && getFeature('WebIDE.entrance.file') && treeData.length ? (
                    <WebIdeBtn
                      tooltipText={intl.get({
                        id: 'code-assets.containers.repoOverviewInfo.WebideCanOnlyBePerformed',
                        defaultMessage: '只有分支下才可以进行 WebIDE 操作',
                      })}
                      type="normal"
                      onClick={(e) => {
                        track({
                          action: 'goto_webide',
                          page: 'Repo-Files',
                        });

                        this.goWebIde(e, '');
                      }}
                      style={{ marginRight: 8 }}
                      className="cell"
                      ipSetting={ipSetting}
                      project_clone_download={project_clone_download}
                    >
                      WebIDE
                    </WebIdeBtn>
                  ) : null}
                  {this.flowButtonComponent()}
                </React.Fragment>
              ) : null}
              <CloneBtn {...this.props} />
              <NewAndUploadFile
                {...this.props}
                goNew={this.goNew}
                extraMenu={
                  isArchive === 'false' && foldBtn
                    ? [
                      getFeature('WebIDE.entrance.file') && isInitedLeftTree && treeData.length ? (
                        <WebIdeBtn
                          tooltipText={intl.get({
                            id: 'code-assets.containers.repoOverviewInfo.WebideCanOnlyBePerformed',
                            defaultMessage: '只有分支下才可以进行 WebIDE 操作',
                          })}
                          type="normal"
                          onClick={(e) => {
                            track({
                              action: 'goto_webide',
                              page: 'Repo-Files',
                            });

                            this.goWebIde(e, '');
                          }}
                          style={{ marginRight: 8 }}
                          className="cell"
                          ipSetting={ipSetting}
                          project_clone_download={project_clone_download}
                          inMoreText
                        >
                          WebIDE
                        </WebIdeBtn>
                        ) : null,
                        ...this.flowButtonComponent({ inMoreText: true }),
                      ]
                    : null
                }
              />
            </div>
          </div>
        )}
      </div>
    );
  }
}
